import Vue from 'vue'
import VueRouter from 'vue-router'

function getChildrenMenu (parentId) {
  let menuSlide = []
  if (parentId) {
    const menuHeader = router.app.$store.state.ec.menu.header
    const menuFlatten = router.app.$store.state.ec.menu.flatten

    const menuPatents = function (menuItem) {
      if (!menuItem) { return 0 }
      const parentId = menuItem.parentId
      if (parentId && menuFlatten[parentId]) {
        return menuPatents(menuFlatten[parentId])
      } else {
        return menuItem.id
      }
    }

    let rootParentId = menuPatents(menuFlatten[parentId])
    menuSlide = menuHeader.filter((menu) => {
      // eslint-disable-next-line eqeqeq
      return menu.id == rootParentId
    })
    if (menuSlide[0] && menuSlide[0].children && menuSlide[0].children.length) {
      menuSlide = menuSlide[0].children
    }
  }
  return menuSlide
}

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}

const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

/**
 * @description 创建在 layout 中显示的路由设置
 * @param {Array} routes 动态路由设置
 */
export function createRoutesInLayout (routes = []) {
  const allRoute = []
  const childrenRoute = []

  routes.forEach(route => {
    if (route.meta && route.meta.routeOutLayout === true) {
      allRoute.push(route)
    } else {
      childrenRoute.push(route)
    }
  })
  allRoute.push({
    path: '/',
    redirect: { name: 'index' },
    component: () => import('../layout/header-aside'),
    children: childrenRoute
  })
  return allRoute
}

// 默认的路由
export const constantRoutes = createRoutesInLayout()

/**
 * @description 创建路由
 * @param {Array} routes 路由设置
 */
const createRouter = (routes = []) => new VueRouter({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes
})

// 导出路由
const router = createRouter(constantRoutes)

/**
 * @description 重新设置路由
 * @param {Array} routes 额外追加的路由
 */
export function resetRouter (routes = []) {
  // TODO: 重置更新路由
  // console.log('重置更新路由')
  // console.log(routes)
  router.matcher = createRouter(routes).matcher
}

/**
 * 路由拦截
 * 权限验证
 */

router.beforeEach(async (to, from, next) => {
  // 新窗口打开页面
  if (to.meta.menuSource && to.meta.menuSource.target === '_blank' && to.query.openType !== '_blank') {
    Vue.prototype.$helper.open(Vue.prototype.$helper.addParams(to.path, { openType: '_blank' }))
    return
  }

  router.app.$showLoading({
    title: 'Loading...',
    isFull: true
  })

  try {
    await router.app.$store.dispatch('ec/menu/load', { to: to.fullPath })
    next()
  } catch (error) {
    next(false)
  }
  router.app.$hideLoading()
})

router.afterEach(to => {
  const parentId = router.app.$helper.get(to, 'meta.menuSource.parentId')
  const menus = getChildrenMenu(parentId)

  router.app.$store.commit('ec/menu/asideSet', menus, { root: true })
  // 进度条
  router.app.$hideLoading()
  // 更改标题
  router.app.$helper.title(to.meta.title)
})

router.onError(error => {
  if (error.code === 'MODULE_NOT_FOUND') {
    router.push({
      name: '404'
    })
  }
})

export default router
